namespace PersianDateControls
{
    public sealed class Convertor
    {
        public static string ToPersianDate(System.DateTime? dateTime)
        {
            try
            {
                System.Globalization.PersianCalendar persianCalendar = new System.Globalization.PersianCalendar();
                return (dateTime != null ? string.Format("{0}/{1}/{2}", persianCalendar.GetYear(dateTime.Value).ToString(), persianCalendar.GetMonth(dateTime.Value).ToString("00"), persianCalendar.GetDayOfMonth(dateTime.Value).ToString("00")) : string.Empty);
            }
            catch
            {
                return string.Empty;
            }
        }

        public static System.DateTime? ToGregorianDate(string dateTime)
        {
            try
            {
                dateTime = RepairPersianDate(dateTime);
                return (new System.Globalization.PersianCalendar().ToDateTime(System.Convert.ToInt32(dateTime.Substring(0, 4)), System.Convert.ToInt32(dateTime.Substring(5, 2)), System.Convert.ToInt32(dateTime.Substring(8, 2)), 0, 0, 0, 0));
            }
            catch
            {
                return null;
            }
        }

        private static string RepairPersianDate(string dateTime)
        {
            dateTime = (dateTime.IndexOf("/", 5) == 6 ? string.Format("{0}0{1}", dateTime.Substring(0, 5), dateTime.Substring(5)) : dateTime);
            dateTime = (dateTime.Length == 9 ? string.Format("{0}0{1}", dateTime.Substring(0, 8), dateTime.Substring(8)) : dateTime);
            if (dateTime.Length > 10 ||
                dateTime == string.Empty)
            {
                throw new System.Exception();
            }
            return dateTime;
        }

    }
}
